package cn.fl.communication.controller;

import java.io.FileInputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmm.communication.facade.communication.condition.NopCallBillInfoQC;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.communication.service.INopCallBillInfoService;
import cn.fl.communication.vo.NopCallBillInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysOrgService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;

/**
 * @Description: 号码保护(话单回调通知)记录 控制层
 */
@Controller
@RequestMapping("/communication/nopcallbillinfo")
public class NopCallBillInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(NopCallBillInfoController.class);

	/**
	 * NopCallBillInfo 服务层BEAN
	 */
	@Autowired
	private INopCallBillInfoService nopCallBillInfoService;

	@Autowired
	private ISysOrgService sysOrgService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
		
		ModelAndView view = new ModelAndView("comm/nopCallBillInfo/nopCallBillInfoPage");
		// 事业部
		List<KeyValueVO> orgList = this.sysOrgService.searchBusinessOrgList();
		view.addObject("orgListList", orgList);

		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "toListPage", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String callerNo = request.getParameter("searchCallerNo");//主叫号码
		String calleeNo = request.getParameter("searchCalleeNo");//被叫号码
		String yNo = request.getParameter("searchYNo");//中间号码Y
		String buOrgCd = request.getParameter("searchBuOrgCd");//所属事业部
		String calleeNm = request.getParameter("searchCalleeNm");//被叫名称
		String initiatorNm = request.getParameter("searchInitiatorNm");//申请人名称
		String mappingId = request.getParameter("searchMappingId");//绑定ID

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		NopCallBillInfoQC qc = new NopCallBillInfoQC();
		if (StringUtils.isNotEmpty(callerNo)) {
			qc.setCallerNo(callerNo);
		}
		if (StringUtils.isNotEmpty(calleeNo)) {
			qc.setCalleeNo(calleeNo);
		}
		if (StringUtils.isNotEmpty(yNo)) {
			qc.setyNo(yNo);
		}
		if (StringUtils.isNotEmpty(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotEmpty(calleeNm)) {
			qc.setCalleeNm(calleeNm);
		}
		if (StringUtils.isNotEmpty(initiatorNm)) {
			qc.setInitiatorNm(initiatorNm);
		}
		if (StringUtils.isNotEmpty(mappingId)) {
			qc.setMappingId(mappingId);
		}
		page.setCondition(qc);
		BaseLogUtils.info(logger, "initList", "加载列表页面.查询条件：" + JSON.toJSONString(qc));

		Pager pager = this.nopCallBillInfoService.searchNopCallBillInfoPage(page);
		List<NopCallBillInfoVO> list = (List<NopCallBillInfoVO>) pager.getResultList();
		ListPageVO<NopCallBillInfoVO> listPage = new ListPageVO<NopCallBillInfoVO>(list, pager.getTotalCount());
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "initList", "加载列表页面.耗时：" + (endTm-startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 打包下载  （关联关系表 批量下载）
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/zipDownload.do", method = {RequestMethod.GET, RequestMethod.POST})
	public DataResultVO zipDownload(HttpServletRequest request, HttpServletResponse response) {

		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "zipDownload", "压缩录音下载.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "录音下载成功");

		//获取数据
		String abcUrl = request.getParameter("abcUrl");

		if (StringUtils.isEmpty(abcUrl)) {
			BaseLogUtils.info(logger, "zipDownload", "录音附件路径不能为空");
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("附件路径不能为空");
			return result;
		}

		String uuid = UUID.randomUUID().toString().replace("-", "");
		String tmpZipFileName = uuid + ".zip";//临时名称
		try {
			ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-Disposition", "attachment; filename=" + tmpZipFileName);
			request.setCharacterEncoding("UTF-8");
			try {
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(abcUrl);
					String fileName=abcUrl.substring(abcUrl.lastIndexOf("/")+1,abcUrl.length());

					out.putNextEntry(new ZipEntry(fileName));
					//下载的文件名写入list
					int bytesRead;
					while (-1 != (bytesRead = fis.read(buffer, 0, buffer.length))) {
						out.write(buffer, 0, bytesRead);
					}
				} catch (Exception e) {
					BaseLogUtils.error(logger, "batchDownload", "下载文件循环中失败!", e);
				} finally {
					if (null != out) {
						out.flush();
						out.closeEntry();
					}
					if (null != fis) {
						fis.close();
						fis = null;
					}
				}
			} catch (Exception e) {
				BaseLogUtils.error(logger, "batchDownload", "下载文件失败!", e);
			}
			if (null != out) {
				out.finish();
				out.close();
				out = null;
			}

		} catch (BaseException be) {
			BaseLogUtils.error(logger, "zipDownload", be.getMessage(), be);
		} catch (Exception ex) {
			BaseLogUtils.error(logger, "zipDownload", ex.getMessage(), ex);
		}

		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger, "zipDownload", " 录音下载页面.耗时：" + (endTm - startTm));
		return null;
	}
	
}

